﻿using Jayden.Dll.Core;
using Jayden.Dll.Core.Persistence;
using Jayden.Dll.Core.Persistence.Data.SQLite;
using Jayden.Dll.Core.Persistence.Models;
using System.Collections.Generic;
using Jayden.Dll.Core.Persistence.Data;
using System.Data.Common;

namespace Jayden.Dll.Cards.Poker
{
	public class SQLiteTexasHoldemPlayerHandSummaryDataAccess : SQLiteDataAccess<TexasHoldemPlayerHandSummary>, TexasHoldemPlayerHandSummaryDataAccess
	{
		public SQLiteTexasHoldemPlayerHandSummaryDataAccess(Configuration config, UnitOfWork uow, Entity entity) : base(config, uow, entity) { }

		public List<TexasHoldemPlayerHandSummary> Read(string playerName)
		{
			string selectCommandText = Helper.GenerateSelect(Entity, Entity["PlayerName"]);
			using (DbCommandProxy selectCommand = CreateCommand(selectCommandText))
			{
				CreateParameter(selectCommand, "PlayerName", playerName);
				using (DbDataReader reader = selectCommand.Command.ExecuteReader())
				{
					return new List<TexasHoldemPlayerHandSummary>(EnumerateFromReader(reader));
				}
			}
		}

		public List<TexasHoldemPlayerHandSummary> ReadByHandId(long handId)
		{
			string selectCommandText = Helper.GenerateSelect(Entity, Entity["HandId"]);
			using (DbCommandProxy selectCommand = CreateCommand(selectCommandText))
			{
				CreateParameter(selectCommand, "HandId", handId);
				using (DbDataReader reader = selectCommand.Command.ExecuteReader())
				{
					return new List<TexasHoldemPlayerHandSummary>(EnumerateFromReader(reader));
				}
			}
		}

		public IEnumerable<TexasHoldemPlayer> EnumeratePlayerFromReader(System.Data.Common.DbDataReader reader)
		{
			while (reader.Read())
			{
				TexasHoldemPlayer player = new TexasHoldemPlayer();
				player.PlayerName = reader["PlayerName"].ToString();
				player.HandCount = int.Parse(reader["HandCount"].ToString());
				player.CardsCount = int.Parse(reader["CardsCount"].ToString());
				player.ProviderName = "PokerStars";
				yield return player;
			}
		}

		public List<TexasHoldemPlayer> ReadPlayersLike(string playerName)
		{
			string selectCommandText = Helper.GenerateSelect(new string[] { "DISTINCT(PlayerName) AS PlayerName", "COUNT(*) AS HandCount", "COUNT(PlayerHand) AS CardsCount" }, Entity.Table.TableName, "PlayerName LIKE @PlayerName", new string[] { "PlayerName" }, new string[] { "HandCount DESC", "PlayerName ASC" }, null, null);
			using (DbCommandProxy selectCommand = CreateCommand(selectCommandText))
			{
				CreateParameter(selectCommand, "PlayerName", playerName);
				using (DbDataReader reader = selectCommand.Command.ExecuteReader())
				{
					return new List<TexasHoldemPlayer>(EnumeratePlayerFromReader(reader));
				}
			}
		}
	}
}
